from fastapi import APIRouter
from app.schemas.xm.monitor_buy import MonitorBuyCreateReq, MonitorBuyCreate, MonitorBuyOut
from app.crud.xm.monitor_buy import (
    create_monitor_buy, 
    get_monitor_buy_page,
    get_by_user_archive_price,
    get_monitor_buy_by_uid,
    expire_monitor_buy,
)
from app.api.deps import SessionDep, CurrentUser
from datetime import datetime, timedelta
from fastapi.exceptions import HTTPException
from app.core.logger import logger
from app.core.utils import yuan_str_to_cents

router = APIRouter(prefix="/monitor-buy", tags=["monitor-buy"])

@router.post("/create", response_model=MonitorBuyOut)
async def create_new_monitor_buy(
    session: SessionDep,
    monitor_buy: MonitorBuyCreateReq,
    current_user: CurrentUser
):
    logger.info(f"create_monitor_buy: {monitor_buy}")
    # 查询用户当前监控数量
    monitor_buys = await get_monitor_buy_by_uid(session, current_user.uid)
    if len(monitor_buys) >= 1:
        raise HTTPException(status_code=400, detail="用户已购买1个监控，无法继续购买")
    # 查询是否已挂单
    existing_monitor_buy = await get_by_user_archive_price(
        session,
        current_user.uid,
        monitor_buy.archiveId,
        yuan_str_to_cents(monitor_buy.buyPrice),
    )
    if existing_monitor_buy:
        raise HTTPException(status_code=400, detail="已存在相同价格的挂单")
    
    # 创建挂单
    db_monitor_buy = MonitorBuyCreate(
        uid=current_user.uid,
        nickname=current_user.nickname,
        archiveId=monitor_buy.archiveId,
        archiveName=monitor_buy.archiveName,
        archiveImg=monitor_buy.archiveImg,
        platformId=monitor_buy.platformId,
        buyPrice=yuan_str_to_cents(monitor_buy.buyPrice),
        maxBuyNum=monitor_buy.maxBuyNum,
        days=monitor_buy.days,
        expireAt=datetime.now() + timedelta(days=monitor_buy.days),
    )
    return await create_monitor_buy(session, db_monitor_buy)

@router.get("/list")
async def get_monitor_buy_list(
    session: SessionDep,
    archiveId: int,
    pageNo: int = 1,
    pageSize: int = 100,
):
    return await get_monitor_buy_page(session, archiveId, pageNo, pageSize)

@router.get("/list-by-user")
async def get_monitor_buy_by_user(
    session: SessionDep,
    current_user: CurrentUser,
):
    """
    获取用户购买的监控
    """
    return await get_monitor_buy_by_uid(session, current_user.uid)

@router.post("/cancel")
async def cancel_monitor_buy(
    session: SessionDep,
    current_user: CurrentUser,
    monitor_buy_id: int,
):
    """
    取消用户购买的监控
    """
    await expire_monitor_buy(session, current_user.uid, monitor_buy_id)
    return None